package com.artisan.domain.service;

import com.artisan.admin.FileProperties;
import com.artisan.util.FileUtil;
import com.artisan.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.core.io.Resource;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Service
public class FileService {

  private final Path fileStorageLocation; // 文件在本地存储的地址
  private final Path fileRelativePath; // 文件相对路径

  @Autowired
  public FileService(FileProperties fileProperties) throws IOException {
    this.fileStorageLocation =
        Paths.get(fileProperties.getUploadDir()).toAbsolutePath().normalize();
    this.fileRelativePath = Paths.get(fileProperties.getUploadDir()).normalize();
    Files.createDirectories(this.fileStorageLocation);
  }

  /**
   * 存储文件到系统
   *
   * @param file 文件
   * @return 文件名
   */
  public String storeFile(MultipartFile file) throws IOException {
    // Normalize file name
    // String fileName = StringUtils.cleanPath(file.getOriginalFilename());
    String fileName =
        RandomUtil.Str(15) + "." + FileUtil.getExtensionName(file.getOriginalFilename());

    // Copy file to the target location (Replacing existing file with the same name)
    Path targetLocation = this.fileStorageLocation.resolve(fileName);
    // Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
    FileUtil.saveFile(targetLocation.toAbsolutePath().toString(), file.getInputStream());

    return fileRelativePath.toString() + "/" + fileName;
  }

  /**
   * 加载文件
   *
   * @param fileName 文件名
   * @return 文件
   */
  public Resource loadFileAsResource(String fileName) throws MalformedURLException {

    Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
    Resource resource = new UrlResource(filePath.toUri());
    if (resource.exists()) {
      return resource;
    } else {
      return null;
    }
  }
}
